<template>
    <div>
        <v-toolbar flat>
            <v-toolbar-title>User</v-toolbar-title>
            <v-divider class="mx-4" inset vertical></v-divider>
            <v-btn small color="success" @click="addVClick">
                Add
                <v-icon dark>
                    mdi-plus
                </v-icon>
            </v-btn>
            <v-btn class="ml-2" small color="error" @click="deleteMany">
                Delete
                <v-icon dark>
                    mdi-delete
                </v-icon>
            </v-btn>
            <v-spacer></v-spacer>
                <v-row>
                    <v-col :cols="4" class="search-input">
                        <v-text-field v-model="query.username" label="username"></v-text-field>
                    </v-col>
                    <v-col :cols="4" class="search-input">
                        <v-text-field v-model="query.nickname" label="nickname"></v-text-field>
                    </v-col>
                    <v-col :cols="1"  class="search-button">
                        <v-btn icon @click="doSearch">
                            <v-icon>
                                mdi-magnify
                            </v-icon>
                        </v-btn>
                    </v-col>
                    <v-col :cols="1"  class="search-button">
                        <v-btn icon @click="doRefresh">
                            <v-icon>
                                mdi-refresh
                            </v-icon>
                        </v-btn>
                    </v-col>
                </v-row>


        </v-toolbar>

        <v-data-table :server-items-length="total" show-select v-model="selected" :loading="loading" loading-text="Loading... Please wait"
            @update:items-per-page="changeLimit" @update:page="changePage" :headers="headers" :items="desserts"
            :items-per-page="query.limit" class="elevation-1">

            <template v-slot:item.status="{ item }">
                <v-switch @change="changeUserStatus(item)" inset color="indigo" v-model="item.status"></v-switch>
            </template>

            <template v-slot:item.actions="{ item }">
                <v-btn icon x-small class="mr-2" @click="editItem(item)">
                    <v-icon>
                        mdi-pencil
                    </v-icon>
                </v-btn>

                <v-btn icon x-small class="mr-2" @click="deleteItem(item)">
                    <v-icon>
                        mdi-delete
                    </v-icon>
                </v-btn>

                <v-btn icon x-small @click="changePwdVClick(item)">
                    <v-icon>
                        mdi-refresh
                    </v-icon>
                </v-btn>

            </template>
            <template v-slot:no-data>
                <v-btn color="primary" @click="initialize">
                    刷新
                </v-btn>
            </template>
        </v-data-table>

        <v-dialog v-model="addV" width="600">
            <v-card class="px-2">
                <v-card-title>Add User</v-card-title>
                <v-card-text>
                    <v-container>
                        <v-form v-model="addValid" ref="addForm">
                            <v-row>
                                <v-col cols="6">
                                    <v-text-field v-model="addForm.username"
                                        :rules="[formRules.lessThan20, formRules.mustRequired]" :counter="20"
                                        label="username" required></v-text-field>
                                </v-col>
                                <v-col cols="6">
                                    <v-text-field v-model="addForm.password" :rules="[formRules.mustRequired]"
                                        label="password" required></v-text-field>
                                </v-col>
                                <v-col cols="6">
                                    <v-text-field v-model="addForm.nickname"
                                        :rules="[formRules.lessThan20, formRules.mustRequired]" :counter="20"
                                        label="nickname" required></v-text-field>
                                </v-col>
                                <v-col cols="6">
                                    <v-text-field v-model="addForm.email" :rules="[formRules.email, formRules.mustRequired]"
                                        label="email" required></v-text-field>
                                </v-col>
                                <v-col cols="6">
                                    <v-select :rules="[formRules.mustRequired]" item-text="group_name" item-value="id"
                                        v-model="addForm.group_id" :items="group_list" label="group"></v-select>
                                </v-col>
                                <v-col cols="6">
                                    <v-btn @click="doAdd">add</v-btn>
                                    <v-btn class="ml-2" @click="doAddReset">reset</v-btn>
                                </v-col>
                            </v-row>
                        </v-form>
                    </v-container>
                </v-card-text>
            </v-card>
        </v-dialog>

        <v-dialog v-model="editV" width="600">
            <v-card>
                <v-card-title>
                    Edit
                </v-card-title>
                <v-card-text>
                    <v-container>
                        <v-form v-model="addValid" ref="addForm">
                            <v-row>
                                <v-col cols="6">
                                    <v-text-field v-model="editForm.nickname"
                                        :rules="[formRules.lessThan20, formRules.mustRequired]" :counter="20"
                                        label="nickname" required></v-text-field>
                                </v-col>
                                <v-col cols="6">
                                    <v-text-field v-model="editForm.email"
                                        :rules="[formRules.email, formRules.mustRequired]" label="email"
                                        required></v-text-field>
                                </v-col>
                                <v-col cols="6">
                                    <v-select :rules="[formRules.mustRequired]" item-text="group_name" item-value="id"
                                        v-model="editForm.group_id" :items="group_list" label="group"></v-select>
                                </v-col>
                                <v-col cols="6">
                                    <v-btn @click="doEdit">edit</v-btn>
                                    <v-btn class="ml-2" @click="doEditReset">reset</v-btn>
                                </v-col>
                            </v-row>
                        </v-form>
                    </v-container>
                </v-card-text>
            </v-card>
        </v-dialog>




        <v-dialog v-model="changePwdV" width="500">
            <v-card class="px-2">
                <v-card-title>Reset password</v-card-title>
                <v-card-text>
                    <v-form ref="resetPwdForm" lazy-validation>
                        <v-text-field v-model="resetPwdForm.password" :rules="[rules.required]"
                            label="请输入密码"></v-text-field>
                        <v-btn @click="changePwd">提交</v-btn>
                    </v-form>
                </v-card-text>
            </v-card>
        </v-dialog>


        <v-snackbar v-model="snackbar">
            {{ text }}
            <template v-slot:action="{ attrs }">
                <v-btn color="pink" text v-bind="attrs" @click="snackbar = false">
                    Close
                </v-btn>
            </template>
        </v-snackbar>

    </div>
</template>
<script>

import { list, doDelete, doInsert, doUpdate, changeStatus, changePwd } from "@/api/back/user";
import { list as listGroup } from "@/api/back/group";
import md5 from "md5";
import lodash from "lodash";

export default {
    name: "UserView",
    data() {
        return {
            selected: [],
            loading: false,
            text: "",
            snackbar: false,
            rules: {
                required: value => !!value || 'Required.',
                counter: value => value.length <= 20 || 'Max 20 characters',
                email: value => {
                    const pattern = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
                    return pattern.test(value) || 'Invalid e-mail.'
                }
            },
            headers: [
                {
                    text: '#',
                    align: 'start',
                    value: 'id',
                },
                { text: '账号', value: 'username' },
                { text: '昵称', value: 'nickname' },
                { text: '邮箱', value: 'email' },
                { text: '状态', value: 'status' },
                { text: '头像', value: 'avatar' },
                { text: '组', value: 'group_name' },
                { text: '操作', value: 'actions', sortable: false },
            ],
            desserts: [],
            query: {
                page: 1,
                limit: 10,
                username: "",
                nickname: ""
            },
            total:0,
            operateItem: {},
            addV: false,
            addValid: false,
            addForm: {
                username: "",
                password: "",
                nickname: "",
                group_id: null,
                email: ""
            },
            editV: false,
            editValid: false,
            editForm: {
                nickname: "",
                group_id: null,
                email: ""
            },
            formRules: {
                mustRequired: v => !!v || 'this is required',
                lessThan20: v => v.length <= 20 || 'this must be less than 20 characters',
                email: v => /.+@.+/.test(v) || 'E-mail must be valid',
            },

            group_list: [],
            changePwdV: false,
            resetPwdForm: {
                password: "",
                id: ""
            },
        }
    },
    created() {
        this.initialize();
    },
    methods: {
        async initialize() {
            this.loading = true;
            let res = await list(this.query);
            this.loading = false;
            if (res.code == 200) {
                this.desserts = [...res.data];
                this.total = res.count;
            }
        },
        doRefresh(){
            this.query = {
                page: 1,
                limit: 10,
                username: "",
                nickname: ""
            };
            this.initialize();
        },
        doSearch(){
            this.query.page = 1;
            this.initialize();
        },
        changeLimit(val) {
            this.query.page = 1;
            this.query.limit = val;
            this.initialize();
        },
        changePage(val) {
            this.query.page = val;
            this.initialize();
        },
        async editItem(v) {
            let query = {
                page: 1,
                limit: -1
            }
            let res = await listGroup(query);
            if (res.code == 200) {
                let data = res.data;
                this.group_list = [...data];
            }
            this.operateItem = lodash.cloneDeep(v);
            this.editForm = lodash.cloneDeep(v);
            this.editV = true;
        },
        async doEdit() {
            let sdata = lodash.cloneDeep(this.editForm);
            let res = await doUpdate(sdata);
            if (res.code == 200) {
                this.initialize();
                this.editV = false;
            }
            this.text = res.msg;
            this.snackbar = true;
        },
        async doEditReset() {
            this.editForm = lodash.cloneDeep(this.operateItem);
        },
        async deleteItem(v) {
            let ids = [v.id];
            let res = await doDelete(ids);
            if (res.code == 200) {
                this.initialize();
            }
            this.text = res.msg;
            this.snackbar = true;
        },
        async addVClick() {
            let query = {
                page: 1,
                limit: -1
            }
            let res = await listGroup(query);
            if (res.code == 200) {
                let data = res.data;
                this.group_list = [...data];
            }
            this.addV = true;
        },
        async doAdd() {
            let bool = this.$refs.addForm.validate();
            if (bool) {
                let sdata = { ...this.addForm };
                sdata.password = md5(sdata.password);
                let res = await doInsert(sdata);
                if (res.code == 200) {
                    this.initialize();
                }
                this.text = res.msg;
                this.snackbar = true;
            }
        },
        doAddReset() {
            this.addForm = {
                username: "",
                password: "",
                nickname: "",
                group_id: null,
            }
        },
        async deleteMany() {
            let temp = lodash.cloneDeep(this.selected);
            let ids = [];
            temp.map(x => {
                if (x.id != 1) {
                    ids.push(x.id);
                }
            });
            let res = await doDelete(ids);
            if (res.code == 200) {
                this.initialize();
                this.selected = [];
            }
            this.text = res.msg;
            this.snackbar = true;
        },



        changePwdVClick(v) {
            this.operateItem = { ...v };
            this.resetPwdForm.id = this.operateItem.id;
            this.changePwdV = true;
        },
        async changePwd() {
            let bool = this.$refs.resetPwdForm.validate();
            if (bool) {
                let sdata = { ...this.resetPwdForm };
                sdata.password = md5(sdata.password);
                let res = await changePwd(sdata);
                if (res.code == 200) {
                    this.text = res.msg;
                    this.snackbar = true;
                    this.$refs.resetPwdForm.reset();
                    this.changePwdV = false;
                } else {
                    this.text = res.msg;
                    this.snackbar = true;
                }
            }
        },
        async changeUserStatus(val) {
            let temp = lodash.cloneDeep(val);
            let sdata = {
                id: temp.id,
                status: temp.status ? 1 : 0
            };
            let res = await changeStatus(sdata);
            if (res.code == 200) {
                this.initialize();
            }
            this.text = res.msg;
            this.snackbar = true;
        }


    }
}
</script>
<style lang="scss" scoped>
.search-input{
    margin-top: 20px;
}
.search-button{
    margin-top: 10px
}
</style>